package org.yixiu.producer.invoke;

import lombok.extern.slf4j.Slf4j;
import org.yixiu.producer.entity.RpcRequest;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * 服务端请求处理器
 * 为了提⾼服务端的并发度，将每⼀个请求的处理过程放到线程池中
 */
@Slf4j
public class RequestHandler implements Runnable{

    private Socket socket;

    public RequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try(ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream())){
            RpcRequest rpcRequest = (RpcRequest) inputStream.readObject();
            Object service = ServiceMap.lookupService(rpcRequest.getInterfaceName());
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            Object invoke = method.invoke(service, rpcRequest.getParams());
            log.info("Provider output: " + invoke.toString());
            outputStream.writeObject(invoke);
        }catch (Exception e){
            log.error("producer invoke method error",e);
            throw new RuntimeException(e.getMessage());
        }
    }
}
